import {
  URL,
  LOGIN_RETRY_TIME,
  USERS,
  MAX_INPUT_PER_DATE,
} from "../../systems/panyu_jiwei/config.js";
import { jiweiAxios } from "../../systems/panyu_jiwei/axios.js";
import cheerio from "cheerio";
import { getCaptcha } from "../getCaptcha.js";
import { commonUtil } from "../index.js";
import yaml from "js-yaml";
import dayjs from "dayjs";
import omit from "lodash/omit.js";
import cloneDeep from "lodash/cloneDeep.js";

export async function panyuJiweiLogin() {
  let USERS_CONFIG = resetConfig(USERS);
  const validUser = await getValidUser(USERS_CONFIG);
  if (!validUser) return console.log(`${global.community}没有可用账号，请检查用户配置`);
  if (validUser.lastLoginTime && dayjs().isBefore(dayjs(validUser.lastLoginTime).add(20, "minute"))) {
    console.log(
      `社区${global.community}，用户${validUser.username}距离上次登录未过20分钟，不需重新登录`
    );
    validUser.lastLoginTime = dayjs().format();
    writeUserConfig(USERS_CONFIG, validUser);
    global.cookie = validUser.cookie;
    global.user = validUser;
    return true;
  }
  for (let i = 0; i < LOGIN_RETRY_TIME; i++) {
    console.log(`开始第${i + 1}次登录`)
    try {
      // 获取登录cookie
      const res = await jiweiAxios({
        url: URL.LOGIN,
      });
      const $login = cheerio.load(res.data);
      const DYNAMIC_LOGIN_URL = $login(
        'script[src^="/pyjw/ajaxpro/Main_AspCode_ZhuChengXu_Login,"]'
      ).attr("src");

      const cookie =
        res.headers["set-cookie"] && res.headers["set-cookie"][0].split(";")[0];

      global.cookie = cookie;
      // 获取登录验证码
      const { data: captchaRes } = await jiweiAxios({
        url: URL.CAPTCHA,
        responseType: "arraybuffer",
      });
      const buffer = Buffer.from(captchaRes, "binary").toString("base64");
      // console.log(`data:image/jpg;base64,${buffer}`)
      const CAPTCHA = await getCaptcha(`data:image/jpg;base64,${buffer}`);
      if (!/^\d{4}$/.test(CAPTCHA)) {
        continue;
      }
      const LOGIN_RES = await jiweiAxios({
        method: "post",
        url: DYNAMIC_LOGIN_URL.replace("/pyjw", ""),
        data: {
          user: validUser.username,
          password: validUser.password,
          camode: "",
          yam: CAPTCHA,
          isuserca: "",
          checkuseca: "",
          CAmc: "",
          url: URL.BASE_URL + URL.LOGIN,
          CaSerial: "",
        },
        headers: {
          "Ajax-method": "Login",
        },
      });

      // 如果返回空则登录成功，否则登录失败
      if (!LOGIN_RES.data) {
        // 登录之后，要点击一下正方形选择部门，这样这个cookie才会带有部门信息
        const res = await jiweiAxios({
          url: URL.SET_JIGOU_KESHI,
          params: {
            JiGou: validUser.JiGou,
            KeShi: validUser.KeShi,
          },
        });
        if (res.status === 200) {
          global.user = validUser;
          validUser.lastLoginTime = dayjs().format();
          validUser.cookie = cookie;
          if (!validUser?.count?.[global.task]) {
            validUser.count = { [global.task]: 0 };
          }
          writeUserConfig(USERS_CONFIG, validUser);

          // 社区${community}的
          console.log(
            `账号${validUser.username}尝试${i + 1}次登录成功: Cookie=${
              global.cookie
            }`
          );
          return true;
        }
        // continue;
      } else {
        console.log(`第${i + 1}次登录失败，准备重试`)
        await commonUtil.sleep(Math.random() * 5 + 3);
        global.cookie = undefined;
        // console.log("login failed");
        // throw new Error("登录失败");
      }
    } catch (err) {
      console.error(err);
    }
  }
  return false;
}

function resetConfig(allUsers) {
  const tempAllUsers = cloneDeep(allUsers);
  const communities = Object.keys(tempAllUsers);
  communities.forEach((community) => {
    const users = tempAllUsers[community];
    tempAllUsers[community] = users.map((item) => {
      if (isToday(item.lastLoginTime)) {
        return item;
      } else {
        return omit(item, ["lastLoginTime", "count"]);
      }
    });
  });

  return tempAllUsers;
}

function isToday(day) {
  return dayjs().isSame(dayjs(day), "day");
}

function writeUserConfig(originConfig, user) {
  const tempConfig = cloneDeep(originConfig);
  const users = tempConfig[global.community];
  for (let i = 0; i < users.length; i++) {
    if (users[i].username === user.username) {
      users[i] = user;
      break;
    }
  }
  tempConfig[global.community] = users;
  commonUtil.writeToFile(
    yaml.dump(tempConfig, {
      lineWidth: -1,
      sortKeys: true,
    }),
    {
      fileName: "users",
      filePath: "../../config/panyu_jiwei/",
      fileType: "yaml",
    }
  );
}

async function getValidUser(USERS) {
  await commonUtil.selectCommunity(USERS);
  const task = await commonUtil.selectTask();
  const users = USERS[global.community];
  const validUser = users.find((item) => {
    const isTimeValid = isToday(item.lastLoginTime);
    const isLessThanCount =
      (item?.count?.[task] ?? 0) <= MAX_INPUT_PER_DATE;
    return isTimeValid && isLessThanCount;
  });
  return validUser;
}
